package com.xz;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author XZ
 * @create 2021-10-18 21:21
 * https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
 */
public class _104_二叉树的最大深度 {
    //方法一
    public int maxDepth(TreeNode root) {
        return height(root);
    }

    public int height(TreeNode node) {
        if (node == null) return 0;
        return 1 + Math.max(height(node.left), height(node.right));
    }

    //方法二
    //计算二叉树的高度，用层序遍历
    public int height2(TreeNode root) {
        if (root == null) return 0;
        //树的高度
        int hight = 0;
        //储存着每一层元素的数量
        int levelSize = 1;
        Queue<TreeNode> queue = new LinkedList();
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            levelSize--;

            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }
            if (levelSize == 0) {//意味着即将访问下一层
                levelSize= queue.size();
                hight++;
            }
        }
        return hight;
    }
}
